var apiUrl = 'https://wx.arrowgroup.com.cn/api';
const util = require('util');

// 封装api请求
const api = (methods, params) => {
    return new Promise((resolve, reject) => {
        let postData = {
            "jsonrpc": "2.0",
            "method": methods,
            "params": params,
            "id": util.uniqid()
        };
        wx.request({
            url: apiUrl + '?method=' + methods,
            data: postData,
            method: 'POST',
            header: {
                "content-type": "application/json"
            },
            success: function(res) {
                if (res.statusCode === 200) {
                    if (res.data.error) {
                        console.log(res.data.error);
                        wx.hideLoading();
                        if (res.data.error.code === 4003) {
                            console.log('出问题了')
                            wx.showToast({
                                title: '请先登录!',
                                icon: 'loading',
                            });
                            app.globalData.hasUserInfo = true,
                                app.globalData.modalData.isShow = true
                            setTimeout(() => {
                                wx.switchTab({
                                    url: '/pages/user/index'
                                });
                            }, 1000);
                        } else {
                            console.log('第二步')
                            wx.showToast({
                                title: res.data.error.message,
                                icon: 'loading'
                            });
                        }
                    } else {
                        console.log(res.data.result);
                        resolve(res.data.result);
                    }
                } else {
                    console.log(res.data);
                    wx.hideLoading();
                    wx.showToast({
                        title: '请求异常',
                        icon: 'loading'
                    });
                }
            },
            error: function(e) {
                wx.hideLoading();
                wx.showToast({
                    title: '网络出错',
                    icon: 'loading'
                });
            }
        })
    });
};

/**
 * 发起带权限验证的API请求
 * @param methods
 * @param params
 */
function authApi(methods, params = {}) {
    params.token = wx.getStorageSync('token');
    return this.api(methods, params);
}


module.exports.api = api;
module.exports.authApi = authApi;